package service

import (
	"fmt"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)
import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v3/client"
)

// 发送短信
// SendMsg 发送短信
func SendMsg(Phone string, code string, smsCode string, SignName string, id int) error {
	// 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
	// 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378661.html
	client, err := createClient(tea.String("LTAI5tFs4DhW79QzhGn27w2U"), tea.String("n3QKYVbUIkPkuxNEzp7AN7dqiNXp6X"))
	if err != nil {
		return err
	}
	if id == 1 {
		sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
			PhoneNumbers:  tea.String(Phone),
			SignName:      tea.String(SignName),
			TemplateCode:  tea.String(smsCode),
			TemplateParam: tea.String("{\"code\":\"" + code + "\"}"),
		}
		fmt.Println(sendSmsRequest)
		runtime := &util.RuntimeOptions{}
		resp, err := client.SendSmsWithOptions(sendSmsRequest, runtime)
		if err != nil {
			fmt.Println(err)
			return err
		}

		// 将验证码存在redis中
		fmt.Println(util.ToJSONString(resp))
	} else {
		sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
			PhoneNumbers:  tea.String(Phone),
			SignName:      tea.String(SignName),
			TemplateCode:  tea.String(smsCode),
			TemplateParam: tea.String("{\"order\":\"" + code + "\"}"),
		}
		fmt.Println(sendSmsRequest)
		runtime := &util.RuntimeOptions{}
		resp, err := client.SendSmsWithOptions(sendSmsRequest, runtime)
		if err != nil {
			fmt.Println(err)
			return err
		}

		// 将验证码存在redis中
		fmt.Println(util.ToJSONString(resp))
	}
	return err
}

/**
 * 使用AK&SK初始化账号Client
 * @param accessKeyId
 * @param accessKeySecret
 * @return Client
 * @throws Exception
 */
func createClient(accessKeyId *string, accessKeySecret *string) (_result *dysmsapi20170525.Client, _err error) {
	config := &openapi.Config{
		// 必填，您的 AccessKey ID
		AccessKeyId: accessKeyId,
		// 必填，您的 AccessKey Secret
		AccessKeySecret: accessKeySecret,
	}
	// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_result = &dysmsapi20170525.Client{}
	_result, _err = dysmsapi20170525.NewClient(config)
	return _result, _err
}
